#pragma once
#include <iostream>
#include <cerrno>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;

#define PATH_NAME "."
#define PROJ_ID 0

const int SHM_SIZE = 4096;

const int SERVER = 1;
const int CLIENT = 0;

class share_memory
{
public:
    share_memory(int type) : _type(type)
    {
        key_t key = getKey();

        if (type == SERVER)
        {
            _shmid = createShm(key, SHM_SIZE);
        }
        else
        {
            _shmid = getShm(key, SHM_SIZE);
        }

        _addr = attachShm(_shmid);
    }

    ~share_memory()
    {
        detachShm(_addr);

        if (_type == SERVER)
        {
            removeShm(_shmid);
        }
    }

    char* getAddr()
    {
        return _addr;
    }

private:
    int   _type  = 0;
    int   _shmid = 0;
    char* _addr  = nullptr;

private:
    key_t getKey()
    {
        key_t key = ftok(PATH_NAME, PROJ_ID);

        if (key < 0)
        {
            perror("getKey");
            exit(1);
        }

        return key;
    }

    int shmgetHelper(key_t key, int size, int flags)
    {
        int id = shmget(key, SHM_SIZE, flags);
        if (id < 0)
        {
            perror("createShm");
            exit(1);
        }
        return id;
    }

    int createShm(key_t key, int size)
    {
        umask(00);
        int id = shmgetHelper(key, size, IPC_CREAT | IPC_EXCL | 0664);
        return id;
    }

    int getShm(key_t key, int size)
    {
        int id = shmgetHelper(key, size, IPC_CREAT);
        return id;
    }

    int removeShm(int id)
    {
        int ret = shmctl(id, IPC_RMID, nullptr);
        if (ret < 0)
        {
            perror("removeShm");
            exit(1);
        }
        return ret;
    }

    struct shmid_ds getShmDs(int id)
    {
        struct shmid_ds shm;
        int             ret = shmctl(id, IPC_STAT, &shm); // must have permission
        if (ret < 0)
        {
            perror("getShmDs");
            exit(1);
        }
        return shm;
    }

    int setShmDs(int id, struct shmid_ds* shm)
    {
        int ret = shmctl(id, IPC_SET, shm);
        if (ret < 0)
        {
            perror("setShmDs");
            exit(1);
        }
        return ret;
    }

    char* attachShm(int id)
    {
        char* addr = (char*)shmat(id, nullptr, 0);
        if (addr == 0)
        {
            perror("attachShm");
            exit(1);
        }
        return addr;
    }

    int detachShm(void* addr)
    {
        int ret = shmdt(addr);
        if (ret < 0)
        {
            perror("detachShm");
            exit(1);
        }
        return ret;
    }
};

class svr_shm : public share_memory
{
public:
    svr_shm() : share_memory(SERVER)
    {}
};

class cli_shm : public share_memory
{
public:
    cli_shm() : share_memory(CLIENT)
    {}
};
